package com.lyl.security.common.sercurity.service.impl;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.map.MapUtil;
import cn.hutool.jwt.JWTUtil;
import com.lyl.security.common.sercurity.model.dto.UserDTO;
import com.lyl.security.common.sercurity.service.LoginService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

@Slf4j
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {
    private final AuthenticationManager authenticationManager;
    public static final String PRIVATE_KEY = "luo@123456";

    @Override
    public String login(UserDTO dto) {
        log.info("方法名: login,  请求参数: dto = [" + dto + "]");
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(dto.getUsername(),dto.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (authenticate.isAuthenticated()){
            //验证成功
            //SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            //生成token
            String token = JWTUtil.createToken(MapUtil.builder("userId", (Object) "1").build(), PRIVATE_KEY.getBytes(StandardCharsets.UTF_8));
            token = Base64Encoder.encode(token);
            return token;
        }
        return "登录失败";
    }
}
